import axios from 'axios'
import { requestCode, token } from '@/core/config.js'
import store from '@/store';
import { Toast, Dialog, Notify } from 'vant';
import Cryptojs from 'crypto-js';
import IngotCookie from '@/utils/cookie.js';
// import { type } from 'os';

const TOKEN_EXPIRE = requestCode.TOKEN_EXPIRE

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api 的 base_url // 使用当前域
  timeout: 30000 // 请求超时时间
})

// console.log("URL",getUrlStr('token'))
// console.log("===service===",service.interceptors)
// request拦截器

service.interceptors.request.use(
  config => {
    // 如果是refreshToken，使用 basic token
    // if(config.params.isVinInfo != undefined || config.params.isVinInfo ){
    //   this.vinBl = true
    // }
    // console.log("config",config);
    let header_arr = [
      IngotCookie.get('user_id'),
      IngotCookie.get('source'),
      IngotCookie.get('device_id'),
      IngotCookie.get('sign')
    ];
    let arr_mdr = '';
    let option_arr = [];
    let all = [];

    if(config.method === "post"){
      // console.log("POST"); // POST 请求
      if(config.data!=undefined){
        // console.log("is config body")
        option_arr = Object.values(config.data).map(String);
        all = option_arr.concat(header_arr).sort();
        // console.log("option_arr",all)
      }else{
        all = header_arr.sort();
      }
      for (let i = 0; i < all.length; i++) {
        if (i == all.length - 1) {
          arr_mdr += all[i];
        } else {
          arr_mdr += all[i] + '&';
        }
      }
    
      // console.log("排序后的list：",all)
      // console.log("编码后：",encodeURIComponent(arr_mdr))
      // console.log("Cryptojs",Cryptojs.HmacMD5(encodeURIComponent(arr_mdr),IngotCookie.get('sign')).toString());
      if (!(config.data instanceof FormData)) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        // config.data = Qs.stringify(config.data);
        // console.log("data",config.data)
      } 
      config.headers['TOKEN'] = IngotCookie.get('token');
      config.headers['TIMESTAMP'] = Date.parse(new Date()).toString().substr(0, 10);
      config.headers['SOURCE'] = IngotCookie.get('source');
      config.headers['DEVICE-ID'] = IngotCookie.get('device_id');
      config.headers['SIGN-RESULT'] = Cryptojs.HmacMD5(encodeURIComponent(arr_mdr),IngotCookie.get('sign')).toString();
    } else {

      // GET 请求
      if(config.params!=undefined){
        
        option_arr = Object.values(config.params).map(String);
        all = option_arr.concat(header_arr).sort();

        // console.log("params:",option_arr)
        // console.log("排序后的list：",all)
      }else{
        all = header_arr.sort();
      }
      for (let i = 0; i < all.length; i++) {
        if (i == all.length - 1) {
          arr_mdr += all[i];
        } else {
          arr_mdr += all[i] + '&';
        }
      }
      // console.log("编码前：",arr_mdr)
      // console.log("编码后：",encodeURIComponent(arr_mdr))
      // console.log("最终加密：",Cryptojs.HmacMD5(encodeURIComponent(arr_mdr),IngotCookie.get('sign')).toString());

      // console.log("is config params ==",option_arr.concat(header_arr).sort())
      // console.log("编码后:",arr_mdr)
      if(store.state.token !== ''){
        config.headers['TOKEN'] = IngotCookie.get('token');
        config.headers['TIMESTAMP'] = Date.parse(new Date()).toString().substr(0, 10);
        config.headers['SOURCE'] = IngotCookie.get('source');
        config.headers['DEVICE-ID'] = IngotCookie.get('device_id');
        config.headers['SIGN-RESULT'] = Cryptojs.HmacMD5(encodeURIComponent(arr_mdr),IngotCookie.get('sign')).toString();
      }
    }
    
    // console.log("headers === ",config.headers)
    return config
  },
  error => {
    // Do something with request error
    console.log('request拦截器',error) // for debug
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非99990200是抛错 可结合自己业务进行修改
     */
    // console.log("response",response)
    const res = response.data
    if (res.code !== requestCode.SUCCESS) {
      console.log("====== response 拦截器 error ======");
      console.log(res.code,TOKEN_EXPIRE);
      if (Number(res.code) === TOKEN_EXPIRE || Number(res.code)=== 1240) {
        console.log('进入token失效逻辑。。。');
        const toast = Toast.loading({
          duration: 0,       // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: res.message
        });
        
        let second = 3;
        const timer = setInterval(() => {
          second--;
          if (second) {
            toast.message = res.message;
          } else {
            IngotCookie.get('source');
            clearInterval(timer);
            Toast.clear();
            console.log('token失效了，客户端准备跳转。。');
            if(IngotCookie.get('source')=='ios'){
              console.log(IngotCookie.get('source'))
              window.webkit.messageHandlers.NoticeTokenDisabled.postMessage(res.code+'_'+res.message);
            }else if(IngotCookie.get('source')=='android'){
              console.log(IngotCookie.get('source'))
              window.AndroidWebView.NoticeTokenDisabled("true", res.code, res.message);
            }
            console.log('gotologinPage', res.message)
          }
        }, 1000);

       
        // Dialog.alert({
        //   title: '抱歉',
        //   message: res.message
        // }).then(()=>{
        //   store.dispatch('FedLogOut').then(() => {
        //     location.reload()
        //   })
        // })
      } else {
        console.log(res.message)
        // Notify({
        //   message: res.message,
        //   duration: 3000
        // })
      }
      return Promise.reject('error')
    } else {
      // console.log("success")
      return response.data
    }
  },
  error => {
    console.log("====== error 接口 error ======",error.response.data)
    const response = error.response
    let message = error.response.data.message
    if (response) {
      if (response.data) {
        const temp = response.data.message
        if (temp && temp.length > 0) {
          message = temp
        }
        if (response.data.code === TOKEN_EXPIRE) {
          // store.dispatch('FedLogOut').then(() => {
          //   location.reload() // 为了重新实例化vue-router对象 避免bug
          // })
        }
      }
    }
    // console.log("message",message)
    Toast.fail(message);
    return Promise.reject(error)
  }
)

export default service
